package com.zy.nft_system.config;

import com.zy.nft_system.exception.MyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 这是那头猪？
 * @version 1.0
 * @description: TODO
 * @date 2022/12/18 9:38
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader("token");
        String userId = request.getHeader("userId");
        if (((token == null) || ( userId == null))){
            throw new MyException("用户还为登录请登录");
        }
        String s1 = stringRedisTemplate.opsForValue().get("userInfo" + userId);
        Map<String, String> userInfo=null;
        if(s1 != null){
            userInfo = Arrays.stream(s1.replaceAll("[{} ]", "").split(","))
                    .map(s -> s.split("="))
                    .collect(Collectors.toMap(a -> a[0], a -> a[1]));
        }
        // System.out.println(s1);
        // HashMap userInfo = (HashMap) request.getSession().getAttribute("userInfo"+userId);
        if (userInfo == null) {
            throw new MyException("token为空请登录");
        }
        String s = (String) userInfo.get("token" + userId);
        if (!s.equals(token)) {
            throw new MyException("非法token");
        }
        //重新设置过期时间
        stringRedisTemplate.delete("userInfo" + userId);
        stringRedisTemplate.opsForValue().setIfAbsent("userInfo" + userId, String.valueOf(userInfo), Duration.ofMinutes(5));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
